package com.basic.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Objects;

/**
 * 发送电子邮件
 *
 * @author zhaoxy_jn@163.com
 */
@Component
public class EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from ;

    /**
     * 发送无附件的邮件
     * @param subject 主题
     * @param content 内容
     * @param to 收件人 多个收件人用英文逗号隔开
     */
    public void sendGeneralEmail(String subject, String content, String to) throws MessagingException {
        this.sendEmail(subject, content, to, null);
    }

    /**
     * 发送带附件的邮件
     * @param subject 主题
     * @param content 内容
     * @param to 收件人 多个收件人用英文逗号隔开
     * @param filePaths 文件路径 全路径
     */
    public void sendAttachmentsEmail(String subject, String content, String to,String[] filePaths) throws MessagingException {
        this.sendEmail(subject, content, to, filePaths);
    }


    /**
     * 发送邮件公用方法
     * @param subject 主题
     * @param content 内容
     * @param to 收件人 多个收件人用英文逗号隔开
     * @param filePaths 文件路径 全路径
     * @throws MessagingException 异常
     */
    private void sendEmail(String subject, String content, String to, String[] filePaths) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        helper.setFrom(from);
        // 设置收件人
        helper.setTo(to);
        // 设置邮件主题
        helper.setSubject(subject);
        // 设置邮件内容 true 表示启动HTML格式的邮件
        helper.setText(content,true);
        // 添加附件
        if (filePaths != null) {
            for (String filePath : filePaths) {
                FileSystemResource file = new FileSystemResource(new File(filePath));
                helper.addAttachment(Objects.requireNonNull(file.getFilename()), file);
            }
        }
        // 发送邮件
        mailSender.send(mimeMessage);
    }


}
